﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using SerialPortBll;
using Telerik.WinControls.UI;
using Telerik.WinControls.UI.Localization;

namespace 串口调试助手
{
    public partial class EditCmd : Form
    {
        public static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public EditCmd()
        {
            InitializeComponent();
        }
        // List<String> groupList;
        List<SendDataLog> lst;
        private void EditCmd_Load(object sender, EventArgs e)
        {
            this.radGridView1.TableElement.BeginUpdate();
            RadGridLocalizationProvider.CurrentProvider = new MyCNRadGridLocalizationProvider();
            this.radGridView1.MasterTemplate.DataView.PagingBeforeGrouping = true;
            this.radGridView1.EnableFiltering = true;
            this.radGridView1.MasterTemplate.ShowHeaderCellButtons = true;
            this.radGridView1.MasterTemplate.ShowFilteringRow = false;
            loadData();
            this.radGridView1.TableElement.EndUpdate();

        }

        private void loadData()
        {
            lst = SendDataLogBMO.getAll();
            // groupList = SendDataLogBMO.getGroupList();
            this.radGridView1.DataSource = lst;
            if (lst.Count > 20)
            {
                this.radGridView1.EnablePaging = true;
            }
            else
            {
                this.radGridView1.EnablePaging = false;
            }
            // radGridView1.MasterTemplate.Columns["send_data_log_id"].IsVisible = false;
            // radGridView1.MasterTemplate.Columns["send_name"].HeaderText = "名称";
            // radGridView1.MasterTemplate.Columns["send_data_content"].HeaderText = "发送内容";

            // radGridView1.MasterTemplate.Columns["send_mode"].HeaderText = "模式";
            GridViewComboBoxColumn clmn = radGridView1.MasterTemplate.Columns["send_mode"] as GridViewComboBoxColumn;
            clmn.DataSource = new string[] { SEND_MODE.HEX.ToString(), SEND_MODE.ASCII.ToString() };

            // radGridView1.MasterTemplate.Columns["create_dt"].HeaderText = "创建时间";
            // radGridView1.MasterTemplate.Columns["send_times"].HeaderText = "发送次数";
            // radGridView1.MasterTemplate.Columns["status"].HeaderText = "状态";
            //// radGridView1.MasterTemplate.Columns["status"] = GridViewComboBoxColumn

            GridViewComboBoxColumn clst = radGridView1.MasterTemplate.Columns["status"] as GridViewComboBoxColumn;
            clst.DataSource = new string[] { STATUS.在用.ToString(), STATUS.作废.ToString() };

            GridViewComboBoxColumn clgp = radGridView1.MasterTemplate.Columns["group_name"] as GridViewComboBoxColumn;

            List<WorkGroup> lsta = WorkGroupBMO.getAll();
            List<String> arst = new List<string>();
            foreach (var v in lsta)
            {
                arst.Add(v.Group_name);
            }
            clgp.DataSource = arst;

            // new string[] { SEND_MODE.HEX.ToString(), SEND_MODE.ASCII.ToString() };
            //WorkGroupBMO.getAll();
            //clgp.DisplayMember = "Group_name";
            //clgp.FieldName = "Group_name";            
            //clgp.ValueMember = "Group_no";


            // radGridView1.MasterTemplate.Columns["group"].HeaderText = "分组";
            // radGridView1.MasterTemplate.Columns["use_dt"].HeaderText = "状态时间";
            // radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; //全部填充
            //radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.None;
            //this.radGridView1.MasterTemplate.BestFitColumns();
            //this.radGridView1.BestFitColumns(BestFitColumnMode.HeaderCells);
            //radMultiColumnComboBox1.DataSource = lst;
            //radMultiColumnComboBox1.DisplayMember = "Send_name";
            //radMultiColumnComboBox1.Columns[0].IsVisible = false;
            //radMultiColumnComboBox1.Columns[1].HeaderText = "名称";
            //radMultiColumnComboBox1.Columns[2].HeaderText = "模式";
            //radMultiColumnComboBox1.Columns[2].IsVisible = false;
            ////radMultiColumnComboBox1.Columns[2].FormatString = "发送模式{0}";
            //radMultiColumnComboBox1.Columns[3].HeaderText = "发送内容";
            ////radMultiColumnComboBox1.Columns[3].AutoSizeMode = Telerik.WinControls.UI.BestFitColumnMode.AllCells;//.DisplayedDataCells;
            //// radMultiColumnComboBox1.
            ////radMultiColumnComboBox1.Columns[4].HeaderText = "创建时间";
            //radMultiColumnComboBox1.Columns[4].IsVisible = false;
            //radMultiColumnComboBox1.Columns[5].IsVisible = false;
            //radMultiColumnComboBox1.Columns[6].IsVisible = false;
            //radMultiColumnComboBox1.Columns[7].IsVisible = false;
            //radMultiColumnComboBox1.Columns[8].HeaderText = "分组";
        }

        private void radGridView1_RowsChanging(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e)
        {
            if (e.Action == Telerik.WinControls.Data.NotifyCollectionChangedAction.Remove)
            {
                if (radGridView1.SelectedRows.Count == 1)
                {
                    DialogResult dialogResult = MessageBox.Show("确认删除该行？删除后不可恢复！", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dialogResult != DialogResult.OK)
                    {
                        e.Cancel = true;
                    }
                }
                else if (radGridView1.SelectedRows.Count > 1 && radGridView1.SelectedRows[0].Equals(e.OldItems[0]))
                {
                    DialogResult dialogResult = MessageBox.Show("确认删除选中的" + radGridView1.SelectedRows.Count + "行吗？删除后不可恢复！", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dialogResult != DialogResult.OK)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void radGridView1_RowsChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e)
        {
            try
            {
                //UpdatePanelInfo(this.radGridView1.CurrentRow);
                if (e.Action == Telerik.WinControls.Data.NotifyCollectionChangedAction.Remove)
                {

                    foreach (GridViewDataRowInfo ri in e.OldItems)
                    {
                        //  GridViewDataRowInfo ri = e.OldItems[0] as GridViewDataRowInfo;
                        int rlt = SendDataLogBMO.delete((int)ri.Cells[0].Value);
                        if (rlt > 0)
                        {
                            log.Debug("====成功删除行:" + ri.Cells[0].Value);
                            showStatusMessage("成功删除行: " + ri.Cells[1].Value, 5000, new object[] { Color.Green });
                        }
                        else
                        {
                            log.Debug("==== 删除失败！");
                            // MessageBox.Show("删除失败！");
                            showStatusMessage("删除失败", 5000, new object[] { Color.Red });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                showStatusMessage("编辑发生异常", new object[] { Color.Red });
                log.Error("编辑发生异常", ex);
            }
        }

        private void radGridView1_UserDeletedRow(object sender, GridViewRowEventArgs e)
        {
            // SendDataLogBMO.delete((int)e,.Row.Cells[0].Value);// radGridView1.MasterTemplate.Rows[e.Row.Index].Cells[0].Value);
        }

        private void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e)
        {
            if (e.EditorType == typeof(RadTextBoxEditor) && this.radGridView1.Columns["send_data_content"].IsCurrent)
            { e.EditorType = typeof(BrowseEditor); }
        }

        private void radGridView1_UserAddedRow(object sender, GridViewRowEventArgs e)
        {

            //if (e.Row.Cells["send_name"].Value == null)
            //{
            //    return;
            //}
            //if (e.Row.Cells["send_data_content"].Value == null)
            //{
            //    return;
            //}
            SendDataLog obj = new SendDataLog();
            obj.Send_name = e.Row.Cells["Send_name"].Value.ToString();
            obj.Send_mode = e.Row.Cells["Send_mode"].Value.ToString();
            obj.Send_data_content = e.Row.Cells["Send_data_content"].Value.ToString();
            obj.Create_dt = (DateTime)e.Row.Cells["Create_dt"].Value;
            obj.Status = e.Row.Cells["Status"].Value.ToString();
            WorkGroup wkObj = WorkGroupBMO.selectObjByName(e.Row.Cells["group_name"].Value.ToString());
            obj.Group_no = wkObj.Group_no;
            obj.WorkGroup = wkObj;
            obj.Group_name = wkObj.Group_name;

            if (SendDataLogBMO.save(obj) > 0)
            {
                showStatusMessage("新增成功！", new object[] { Color.Green });
                SendDataLog newObj = SendDataLogBMO.selectObjByName(obj.Send_name);
                e.Row.Cells["send_data_log_id"].Value = newObj.Send_data_log_id;
            }
            else
            {
                showStatusMessage("新增失败！", new object[] { Color.Red });
                e.Row.Delete();
            }
        }

        private void radGridView1_UserAddingRow(object sender, GridViewRowCancelEventArgs e)
        {
            e.Cancel = true;
            if (e.Rows != null && e.Rows.Length > 0)
            {
                //if (e.Rows[0].Cells["group_no"].Value != null)
                //{
                //    string grp_no = e.Rows[0].Cells["group_no"].Value.ToString();
                //    if (!groupList.Contains(grp_no))
                //    {
                //        groupList.Add(grp_no);
                //    }
                //}
                GridViewRowInfo rw = e.Rows[0];
                if (rw.Cells["send_name"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_name"].Value.ToString()))
                {
                    showStatusMessage(rw.Cells["send_name"].ColumnInfo.HeaderText + "不能为空!", 3000, new object[] { Color.Red });
                }
                else if (null != SendDataLogBMO.selectObjByName(rw.Cells["send_name"].Value.ToString()))
                {
                    showStatusMessage(rw.Cells["send_name"].Value.ToString() + "名称已经存在！", 3000, new object[] { Color.Red });
                }
                else if (rw.Cells["send_mode"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_mode"].Value.ToString()))
                {
                    showStatusMessage(rw.Cells["send_mode"].ColumnInfo.HeaderText + "不能为空", 3000, new object[] { Color.Red });
                }
                else if (rw.Cells["send_data_content"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_data_content"].Value.ToString()))
                {
                    showStatusMessage(rw.Cells["send_data_content"].ColumnInfo.HeaderText + "不能为空", 3000, new object[] { Color.Red });
                }
                else
                {
                    e.Cancel = false;
                }
            }
        }
        private void radGridView1_DefaultValuesNeeded(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells["status"].Value = STATUS.在用;
            e.Row.Cells["create_dt"].Value = DateTime.Now;
            e.Row.Cells["group_name"].Value = COMMON.DEFAULT_GROUP_NO;
            showStatusMessage("按Esc键取消新增");
        }

        private void EditCmd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.F:
                        //查找
                        //radGridView1.AllowSearchRow = !radGridView1.AllowSearchRow;
                        radCheckBoxElement2.PerformClick();
                        break;
                    case Keys.G:
                        radCheckBoxElement1.PerformClick();
                        break;
                    case Keys.N:
                        radCheckBoxElement_add.PerformClick();
                        break;
                }
            }
        }

        private void EditCmd_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            MessageBox.Show("ctrl+f查询");
        }

        private void radCheckBoxElement1_CheckStateChanged(object sender, EventArgs e)
        {

            radGridView1.ShowGroupPanel = radCheckBoxElement1.Checked;

        }

        private void radCheckBoxElement2_CheckStateChanged(object sender, EventArgs e)
        {
            radGridView1.AllowSearchRow = radCheckBoxElement2.Checked;
        }

        private void radCheckBoxElement_add_CheckStateChanged(object sender, EventArgs e)
        {
            radGridView1.AllowAddNewRow = radCheckBoxElement_add.Checked;
        }

        private void showStatusMessage(string msg, params object[] args)
        {
            showStatusMessage(msg, 5000, args);
        }
        /// <summary>
        /// 更新状态栏消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="timer"></param>
        /// <param name="args"></param>
        private void showStatusMessage(string msg, int timer = 5000, params object[] args)
        {
            setStatusInfo(msg, args);
            System.Timers.Timer
             myTimer = new System.Timers.Timer();
            myTimer.Interval = timer;
            myTimer.Elapsed += MyTimer_Tick;
            myTimer.AutoReset = false;
            myTimer.Start();
        }
        private void MyTimer_Tick(object sender, EventArgs e)
        {
            setStatusInfo("就绪");
        }

        /// <summary>
        /// 设置状态栏文本
        /// </summary>
        /// <param name="message"></param>
        /// <param name="args"><see cref="文本颜色、背景颜色、图标"/></param>
        private void setStatusInfo(String message, params object[] args)
        {
            Action<object[]> aSetParams = (v =>
             {
                 if (v.Length > 0)
                 {
                     radLabelElement_Info.ForeColor = (Color)v[0];
                     if (v.Length == 2)
                     {
                         radLabelElement_Info.BackColor = (Color)v[1];
                     }
                 }
                 else
                 {
                     radLabelElement_Info.ForeColor = Color.Black;
                     radLabelElement_Info.BackColor = SystemColors.Control;
                 }
             });

            if (radStatusStrip1.InvokeRequired)
            {
                this.Invoke(new Action<String>(a =>
                {
                    radLabelElement_Info.Text = a;
                    aSetParams(args);
                }), message);
            }
            else
            {
                radLabelElement_Info.Text = message;
                aSetParams(args);
            }
        }

        private void radGridView1_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            //GridViewDataColumn column = e.Column as GridViewDataColumn;
            //if (column != null && column.FieldName == "FileName")
            //{
            //    object value = null;
            //    if (e.Value != null && !Convert.IsDBNull(e.Value))
            //    {
            //        value = Image.FromFile(e.Value.ToString());
            //    }
            //    this.radGridView1.CurrentRow.Cells["Image"].Value = value;
            //} 
        }

        private void radGridView1_ValueChanging(object sender, ValueChangingEventArgs e)
        {
            log.Debug(e); 

            e.Cancel = true;
            string currentName = radGridView1.MasterTemplate.CurrentColumn.Name;
            if ("send_name".Equals(currentName) && String.IsNullOrWhiteSpace(e.NewValue.ToString())){
                log.Error("发送名称不能为空！");
            }

            //if (e. != null && e.Rows.Length > 0)
            //{
            //    //if (e.Rows[0].Cells["group_no"].Value != null)
            //    //{
            //    //    string grp_no = e.Rows[0].Cells["group_no"].Value.ToString();
            //    //    if (!groupList.Contains(grp_no))
            //    //    {
            //    //        groupList.Add(grp_no);
            //    //    }
            //    //}
            //    GridViewRowInfo rw = e.Rows[0];
            //    if (rw.Cells["send_name"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_name"].Value.ToString()))
            //    {
            //        showStatusMessage(rw.Cells["send_name"].ColumnInfo.HeaderText + "不能为空!", 3000, new object[] { Color.Red });
            //    }
            //    else if (null != SendDataLogBMO.selectObjByName(rw.Cells["send_name"].Value.ToString()))
            //    {
            //        showStatusMessage(rw.Cells["send_name"].Value.ToString() + "名称已经存在！", 3000, new object[] { Color.Red });
            //    }
            //    else if (rw.Cells["send_mode"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_mode"].Value.ToString()))
            //    {
            //        showStatusMessage(rw.Cells["send_mode"].ColumnInfo.HeaderText + "不能为空", 3000, new object[] { Color.Red });
            //    }
            //    else if (rw.Cells["send_data_content"].Value == null || String.IsNullOrWhiteSpace(rw.Cells["send_data_content"].Value.ToString()))
            //    {
            //        showStatusMessage(rw.Cells["send_data_content"].ColumnInfo.HeaderText + "不能为空", 3000, new object[] { Color.Red });
            //    }
            //    else
            //    {
            //        e.Cancel = false;
            //    }
            //}
        }
    }
}
